package org.seanye.erp.view.model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.seanye.erp.view.util.DateUtil;
import org.seanye.erp.view.util.DoubleUtil;

public class CsvReader {

    private static final String COMMA = ",";
    private static final String NEW_LINE = "\n";
    private static final int LENGTH = (COMMA+NEW_LINE).length();

    public static String toCsv(final Store store) {
	if (store.howManyWeeks() == 0) {
	    return "";
	} else {
	    StringBuffer buffer = new StringBuffer();
	    for (Iterator<WeekStore> iterator = store.getStores().iterator(); iterator
		    .hasNext();) {
		WeekStore weekStore = iterator.next();
		buffer.append(weekStoreToCsvLine(weekStore)).append(NEW_LINE);
	    }
	    return buffer.toString().substring(0,buffer.length()-LENGTH);
	}
    }

    private static Object weekStoreToCsvLine(WeekStore weekStore) {
	StringBuffer buffer = new StringBuffer();
	buffer.append(DateUtil.format(weekStore.getStartDate())).append(COMMA);
	buffer.append(DoubleUtil.showDouble(weekStore.getPrviousWeekTotal()))
		.append(COMMA);
	buffer.append(DoubleUtil.showDouble(weekStore.getInput()))
		.append(COMMA);
	buffer.append(DoubleUtil.showDouble(weekStore.getTotalStock())).append(
		COMMA);
	// Week days
	for (int i = 0; i < 7; i++) {
	    try {
		StoreItem storeItem = weekStore.getWeekItems().get(i);
		buffer.append(DoubleUtil.showDouble(storeItem.getShipment()))
			.append(COMMA);
	    } catch (ArrayIndexOutOfBoundsException e) {
		buffer.append("0").append(COMMA);
	    }
	}
	buffer.append(DoubleUtil.showDouble(weekStore.totalShipment())).append(
		COMMA);
	buffer.append(DoubleUtil.showDouble(weekStore.getBalance())).append(
		COMMA);
	buffer.append(DoubleUtil.showDouble(weekStore.getWarnNumber())).append(
		COMMA);
	return buffer.toString();
    }

    public static Store read(final File file) throws Exception {
	Store store = new Store();
	String value = readFile(file);
	if (value != null && !value.equals("")) {
	    String[] lines = value.split(NEW_LINE);
	    if (lines.length > 0) {
		for (String line : lines) {
		    store.getStores().add(createWeekStore(line));
		}
	    }
	}
	return store;
    }

    public static void write(Store store, final File file) throws Exception {
	String value = toCsv(store);
	FileWriter fstream = new FileWriter(file);
	BufferedWriter out = new BufferedWriter(fstream);
	out.write(value);
	out.close();
    }

    private static WeekStore createWeekStore(String line) throws Exception {
	String[] items = line.split(COMMA);
	if (items != null && items.length > 0) {
	    WeekStore store = new WeekStore();
	    for (int index = 0; index < items.length; index++) {
		String str = items[index];
		switch (index) {
		case 0:
		    // verify date;
		    Date date = DateUtil.getFirstDayOfWeek(str);
		    store.setStartDate(date);
		    break;
		case 1:
		    store.setPrviousWeekTotal(Double.parseDouble(str));
		    break;
		case 2:
		    store.setInput(Double.parseDouble(str));
		    break;
		case 3:
		    break;
		case 4:
		case 5:
		case 6:
		case 7:
		case 8:
		case 9:
		case 10:
		    List<StoreItem> weekItems = store.getWeekItems();
		    Date currentDate = Calendar.getInstance().getTime();
		    try {
			StoreItem si = weekItems.get(index - 2);
			si.setUpdatedDate(currentDate);
			si.setShipment(Double.parseDouble(str));
		    } catch (Exception e) {
			StoreItem si = new StoreItem(currentDate);
			si.setShipment(Double.parseDouble(str));
			weekItems.add(index - 2, si);
		    }
		    break;
		case 11:
		    // Edit disable
		    break;
		case 12:
		    // Edit disable
		    break;
		case 13:
		    store.setWarnNumber(Double.parseDouble(str));
		default:
		    break;
		}
	    }
	    return store;
	}
	return null;
    }

    private static String readFile(final File file) throws Exception {
	FileInputStream fstream = new FileInputStream(file);
	DataInputStream in = new DataInputStream(fstream);
	BufferedReader br = new BufferedReader(new InputStreamReader(in));
	String strLine;
	StringBuffer buffer = new StringBuffer();
	while ((strLine = br.readLine()) != null) {
	    buffer.append(strLine).append(NEW_LINE);
	}
	in.close();
	return buffer.toString();
    }
}
